package com.njtoyo.taxi.admin.utils.encrypt;

import cn.hutool.core.util.RandomUtil;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAEncryptionUtil {

    private static String PRIVATEKEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC55nYRcozJRWzKei4va3omLGAeAycZgL44xZr3MNPsuNxy77ikF1Fq/ygkfxQ/fcgE3pCQrBPpY0JS5vCeLFV/nIn2mnj5Ub2mVO7Y5+G+d67gwxUw/nxWzFh3z4f88bRhbisI78SLpzcUDT4FxQN7Yfk2kJuYCbXH7ACW9862HTJ9w3rGzcmb9eQA707NHPe4BGrGslvGM5ADiRwVj2dGhvdmzt1hssFP43xXmmYLVOv4vBiV0yZUtbl4n5CfQoYZsiKO0d11l66wr3JvHLivYbXxQpSFCqzcrzA0bm9R5zMlyPthDFKIgLal7GOCB9VSFj1Xkl/xG3PN1YP/st1TAgMBAAECggEBALjT+NmaAX3vh528YoUFH9oqTpooWkyR4w7A8TUJl/sJRS0FSJflEy8FZ1z5+CC0JxUoT6V3YQivhna0Y9FvlMYe1lCX/uUrrxpb4WlJCvn7NqUDcONYcjk+TEs6zCLiEYy5IxJsiQashydpjxvfaHnYzBXDKt+7779I1sFCuoP2x1GRP+TZAMVaGLb05A5X48Dm4p59OS5Q10h9aC0+ymKiv7NJZfrEtqhysoj8T8mAxLQeaipYxmL8Yy21VhWNbkE2DPZDqGY8pf2KAbCMK67AMoug/HwneGk46Q4C/2RGeUinuZSJbLMzwPrgIEaG7CMnnd9pi8cHTkFGX6cdBfECg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UDe2H5NpCbmAm1x+wAlvfOth0yfcN6xs3Jm/XkAO9OzRz3uARqxrJbxjOQA4kcFY9nRob3Zs7dYbLBT+N8V5pmC1Tr+LwYldMmVLW5eJ+Qn0KGGbIijtHddZeusK9ybxy4r2G18UKUhQqs3K8wNG5vUeczJcj7YQxSiIC2pexjggfVUhY9V5Jf8RtzzdWD/7LdUwIDAQAB";
    private static Map<Integer, String> keyMap = new HashMap<>(); // 用于封装随机产生的公钥与私钥

    public static void main(String[] args) {
        //加密字符串
        String message = "df723820";
//        System.out.println("随机生成的公钥为:" + publicKey);
//        System.out.println("随机生成的私钥为:" + privateKey);
        String messageEn = encrypt(message, publicKey);
        System.out.println("加密后的字符串为:" + messageEn);
        String messageDe = decrypt(messageEn);
        System.out.println("还原后的字符串为:" + messageDe);

        System.out.println(0 + RandomUtil.randomNumbers(15));
    }

    //随机生成密钥对
    public static void genKeyPair() {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = null;

        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // 初始化密钥对生成器，密钥大小为96-1024位
        assert keyPairGen != null;
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put(0, publicKeyString);  //0表示公钥
        keyMap.put(1, privateKeyString);  //1表示私钥
    }

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     */
    public static String encrypt(String str, String publicKey) {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = null;
        String outStr = null;

        try {
            pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
        } catch (InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException |
                 NoSuchPaddingException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //RSA加密
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 铭文
     */
    public static String decrypt(String str) {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(PRIVATEKEY);
        RSAPrivateKey priKey = null;
        //RSA解密
        Cipher cipher = null;
        String outStr = null;

        try {
            priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException |
                 IllegalBlockSizeException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return outStr;
    }
}
